class Solution
{
public:
    vector<int> solve(vector<int>& a)
    {
        int n = a.size();
        vector<bool> mp(n + 1, false);
        vector<int> ans;
        stack<int> st;
        for (auto i : a)
        {
            mp[i] = true;
            st.push(i);
            while (mp[n]) n--;
            while (!st.empty() && st.top() > n)
            {
                ans.push_back(st.top());
                st.pop();
            }
        }

        return ans;
    }
};
